﻿using Scriban;
using Scriban.Parsing;
using Scriban.Runtime;

namespace EasyXaf.EntityDesigner.CodeTemplates;

public class TemplateRenderingEngine
{
    private static TemplateContext CreateTemplateContext(object model)
    {
        var context = new TemplateContext();
        var scriptObject = new ScriptObject();
        scriptObject.Import(typeof(CustomTemplateFunctions));
        scriptObject.Import(model);
        context.PushGlobal(scriptObject);
        context.TemplateLoader = new IncludeTemplateFromEmbedded();
        return context;
    }

    public static string Render(string templateName, object model)
    {
        var context = CreateTemplateContext(model);
        var templateLoader = context.TemplateLoader;
        var templatePath = templateLoader.GetPath(context, new SourceSpan(), templateName);
        var templateContent = templateLoader.Load(context, new SourceSpan(), templatePath);
        var template = Template.Parse(templateContent);
        if (template.HasErrors)
        {
            throw new Exception(template.Messages.ToString());
        }
        return template.Render(context);
    }
}
